package com.sky.service.user.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.ShoppingCart;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.admin.DishMapper;
import com.sky.mapper.admin.SetmealMapper;
import com.sky.mapper.user.UserShoppingCartMapper;
import com.sky.service.user.UserShoppingCartService;
import com.sky.utils.GetHttp;
import com.sky.utils.ParseJWTGetId;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
@RequiredArgsConstructor
public class UserShoppingCartServiceImpl extends ServiceImpl<UserShoppingCartMapper, ShoppingCart> implements UserShoppingCartService {
    private final UserShoppingCartMapper userShoppingCartMapper;
    private final DishMapper dishMapper;
    private final SetmealMapper setmealMapper;
    private final ParseJWTGetId parseJWTGetId;
    private final GetHttp getHttp;

    //因为原本写的太乱，所以重构，好像重构过头了
    @CacheEvict(value = "shoppingCart", key = "'用户:' + #shoppingCart.userId")
    @Transactional
    @Override
    public void add(ShoppingCart shoppingCart, ShoppingCartDTO shoppingCartDTO) {
        log.info("Service-shoppingCartDTO:{}", shoppingCartDTO);

        // 验证参数
        validateShoppingCartDTO(shoppingCartDTO);

        // 处理菜品或套餐信息
        if (shoppingCartDTO.getDishId() != null) {
            handleDishItem(shoppingCart, shoppingCartDTO);
        } else {
            handleSetmealItem(shoppingCart, shoppingCartDTO);
        }

        // 保存或更新购物车
        saveOrUpdateShoppingCart(shoppingCart);
    }

    /**
     * 验证购物车DTO参数
     */
    private void validateShoppingCartDTO(ShoppingCartDTO shoppingCartDTO) {
        if (shoppingCartDTO == null) {
            throw new ShoppingCartBusinessException("购物车数据为空");
        }

        if (parseJWTGetId.getUserId(getHttp.getCurrentHttpServletRequest()) == null) {
            throw new ShoppingCartBusinessException("用户ID不能为空");
        }

        // 验证必须有一个ID
        if (shoppingCartDTO.getDishId() == null && shoppingCartDTO.getSetmealId() == null) {
            throw new ShoppingCartBusinessException("菜品ID和套餐ID不能同时为空");
        }
    }

    /**
     * 处理菜品项
     */
    private void handleDishItem(ShoppingCart shoppingCart, ShoppingCartDTO shoppingCartDTO) {
        Dish dish = getAndValidateDish(shoppingCartDTO.getDishId());
        setShoppingCartFromDish(shoppingCart, dish);
        shoppingCart.setDishFlavor(shoppingCartDTO.getDishFlavor());
    }

    /**
     * 处理套餐项
     */
    private void handleSetmealItem(ShoppingCart shoppingCart, ShoppingCartDTO shoppingCartDTO) {
        Setmeal setmeal = getAndValidateSetmeal(shoppingCartDTO.getSetmealId());
        setShoppingCartFromSetmeal(shoppingCart, setmeal);
        shoppingCart.setDishFlavor(shoppingCartDTO.getDishFlavor());
    }

    /**
     * 获取并验证菜品
     */
    private Dish getAndValidateDish(Integer dishId) {
        Dish dish = getDishById(dishId);
        if (dish == null) {
            throw new ShoppingCartBusinessException("菜品不存在");
        }
        if (dish.getStatus() != 1) {
            throw new ShoppingCartBusinessException("菜品已停售");
        }
        return dish;
    }

    /**
     * 获取并验证套餐
     */
    private Setmeal getAndValidateSetmeal(Integer setmealId) {
        Setmeal setmeal = getSetmealById(setmealId);
        if (setmeal == null) {
            throw new ShoppingCartBusinessException("套餐不存在");
        }
        if (setmeal.getStatus() != 1) {
            throw new ShoppingCartBusinessException("套餐已停售");
        }
        return setmeal;
    }

    /**
     * 根据ID查询菜品
     */
    private Dish getDishById(Integer dishId) {
        QueryWrapper<Dish> dishWrapper = new QueryWrapper<Dish>()
                .eq("id", dishId);
        return dishMapper.selectOne(dishWrapper);
    }

    /**
     * 根据ID查询套餐
     */
    private Setmeal getSetmealById(Integer setmealId) {
        QueryWrapper<Setmeal> setmealWrapper = new QueryWrapper<Setmeal>()
                .eq("id", setmealId);
        return setmealMapper.selectOne(setmealWrapper);
    }

    /**
     * 从菜品设置购物车信息
     */
    private void setShoppingCartFromDish(ShoppingCart shoppingCart, Dish dish) {
        shoppingCart.setName(dish.getName());
        shoppingCart.setAmount(dish.getPrice());
        shoppingCart.setImage(dish.getImage());
        shoppingCart.setDishId(dish.getId());
        shoppingCart.setSetmealId(null); // 明确设置为null
    }

    /**
     * 从套餐设置购物车信息
     */
    private void setShoppingCartFromSetmeal(ShoppingCart shoppingCart, Setmeal setmeal) {
        shoppingCart.setName(setmeal.getName());
        shoppingCart.setAmount(setmeal.getPrice());
        shoppingCart.setImage(setmeal.getImage());
        shoppingCart.setSetmealId(setmeal.getId());
        shoppingCart.setDishId(null);
    }

    /**
     * 保存或更新购物车项
     */
    private void saveOrUpdateShoppingCart(ShoppingCart shoppingCart) {
        ShoppingCart existingCart = findExistingShoppingCart(shoppingCart);
        if (existingCart != null) {
            updateShoppingCartQuantity(existingCart);
        } else {
            insertNewShoppingCart(shoppingCart);
        }
    }

    /**
     * 查找已存在的购物车项
     */
    private ShoppingCart findExistingShoppingCart(ShoppingCart shoppingCart) {
        QueryWrapper<ShoppingCart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", shoppingCart.getUserId())
                .eq(shoppingCart.getDishId() != null,"dish_id", shoppingCart.getDishId())
                .eq(shoppingCart.getSetmealId() != null,"setmeal_id", shoppingCart.getSetmealId())
                .eq(shoppingCart.getDishFlavor() != null,"dish_flavor", shoppingCart.getDishFlavor());
        return userShoppingCartMapper.selectOne(queryWrapper);
    }

    /**
     * 更新购物车数量
     */
    private void updateShoppingCartQuantity(ShoppingCart existingCart) {
        existingCart.setNumber(existingCart.getNumber() + 1);
        userShoppingCartMapper.updateById(existingCart);
    }

    /**
     * 插入新的购物车项
     */
    private void insertNewShoppingCart(ShoppingCart shoppingCart) {
        shoppingCart.setNumber(1);
        log.info("插入购物车数据: {}", shoppingCart);
        userShoppingCartMapper.insert(shoppingCart);
    }


    /**
     * 查询购物车
     * @param userId
     * @return
     */
    @Override
    @Cacheable(value = "shoppingCart", key = "'用户:' + #userId")
    public List<ShoppingCart> findAll(Integer userId) {
        return userShoppingCartMapper.selectList(new QueryWrapper<ShoppingCart>()
                                    .eq("user_id", userId));
    }

    /**
     * 查找已存在的购物车项
     */
    private ShoppingCart findExistingShoppingCart(ShoppingCartDTO shoppingCartDTO) {
        QueryWrapper<ShoppingCart> queryWrapper = new QueryWrapper<ShoppingCart>()
                .eq("user_id", parseJWTGetId.getUserId(getHttp.getCurrentHttpServletRequest()));

        if (shoppingCartDTO.getDishId() != null) {
            queryWrapper.eq("dish_id", shoppingCartDTO.getDishId());
            if (shoppingCartDTO.getDishFlavor() != null) {
                queryWrapper.eq("dish_flavor", shoppingCartDTO.getDishFlavor());
            }
        } else {
            queryWrapper.eq("setmeal_id", shoppingCartDTO.getSetmealId());
        }

        return userShoppingCartMapper.selectOne(queryWrapper);
    }

    /**
     * 删除购物车项
     */
    @Transactional
    @Override
    @CacheEvict(value = "shoppingCart", key = "'用户:' + #userId")
    public void deleteById(ShoppingCartDTO shoppingCartDTO, Integer userId) {
        validateShoppingCartDTO(shoppingCartDTO);

        // 先查找对应的购物车项
        ShoppingCart existingCart = findExistingShoppingCart(shoppingCartDTO);

        if (existingCart == null) {
            throw new ShoppingCartBusinessException("购物车项不存在");
        }

        // 如果数量大于1，减少数量
        if (existingCart.getNumber() > 1) {
            existingCart.setNumber(existingCart.getNumber() - 1);
            userShoppingCartMapper.updateById(existingCart);
        } else {
            // 如果数量为1，直接删除
            userShoppingCartMapper.deleteById(existingCart.getId());
        }
    }

    @Transactional
    @Override
    @CacheEvict(value = "shoppingCart", key = "'用户:' + #userId")
    public void deletesById(Integer userId) {
        if (userId == null){
            throw new ShoppingCartBusinessException("用户ID不能为空");
        }
        userShoppingCartMapper.delete(new QueryWrapper<ShoppingCart>()
                            .eq("user_id", userId));
        log.info("删除购物车数据成功");
    }


}







//@CacheEvict(value = "shoppingCart", key = "'用户:' + #shoppingCart.userId")
//@Transactional
//@Override
//public void add(ShoppingCart shoppingCart, ShoppingCartDTO shoppingCartDTO) {
//    log.info("Service-shoppingCartDTO:{}", shoppingCartDTO);
//    if (shoppingCartDTO == null) {
//        throw new ShoppingCartBusinessException("购物车数据为空");
//    }
//
//    // 验证必须有一个ID
//    if (shoppingCartDTO.getDishId() == null && shoppingCartDTO.getSetmealId() == null) {
//        throw new ShoppingCartBusinessException("菜品ID和套餐ID不能同时为空");
//    }
//
//    // 处理菜品
//    if (shoppingCartDTO.getDishId() != null) {
//        QueryWrapper<Dish> dishWrapper = new QueryWrapper<Dish>()
//                .eq("id", shoppingCartDTO.getDishId());
//        Dish dish = dishMapper.selectOne(dishWrapper);
//
//        if (dish == null) {
//            throw new ShoppingCartBusinessException("菜品不存在");
//        }
//
//        if (dish.getStatus() != 1) {
//            throw new ShoppingCartBusinessException("菜品已停售");
//        }
//
//        // 设置购物车信息
//        shoppingCart.setName(dish.getName());
//        shoppingCart.setAmount(dish.getPrice());
//        shoppingCart.setImage(dish.getImage());
//        shoppingCart.setDishId(dish.getId());
//    }
//
//    // 处理套餐
//    if (shoppingCartDTO.getSetmealId() != null) {
//        QueryWrapper<Setmeal> setmealWrapper = new QueryWrapper<Setmeal>()
//                .eq("id", shoppingCartDTO.getSetmealId());
//        Setmeal setmeal = setmealMapper.selectOne(setmealWrapper);
//
//        if (setmeal == null) {
//            throw new ShoppingCartBusinessException("套餐不存在");
//        }
//
//        if (setmeal.getStatus() != 1) {
//            throw new ShoppingCartBusinessException("套餐已停售");
//        }
//
//        // 设置购物车信息
//        shoppingCart.setName(setmeal.getName());
//        shoppingCart.setAmount(setmeal.getPrice());
//        shoppingCart.setImage(setmeal.getImage());
//        shoppingCart.setSetmealId(setmeal.getId());
//    }
//
//    // 设置口味
//    shoppingCart.setDishFlavor(shoppingCartDTO.getDishFlavor());
//
//    // 检查是否已存在相同商品
//    QueryWrapper<ShoppingCart> queryWrapper = new QueryWrapper<>();
//    queryWrapper.eq("user_id", shoppingCart.getUserId())
//            .eq("dish_id", shoppingCart.getDishId())
//            .eq("setmeal_id", shoppingCart.getSetmealId())
//            .eq("dish_flavor", shoppingCart.getDishFlavor());
//
//    ShoppingCart existingCart = userShoppingCartMapper.selectOne(queryWrapper);
//    if (existingCart != null) {
//        // 如果已存在，则增加数量
//        existingCart.setNumber(existingCart.getNumber() + 1);
//        userShoppingCartMapper.updateById(existingCart);
//    } else {
//        // 设置默认数量
//        shoppingCart.setNumber(1);
//        log.info("插入购物车数据: {}", shoppingCart);
//        userShoppingCartMapper.insert(shoppingCart);
//    }
//}
